package com.leon.datalink.core.persistence;

import com.leon.datalink.core.evn.EnvUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 持久化配置管理器
 * 负责管理Actor持久化的配置决策
 * 
 * @author leon
 */
public class PersistenceConfigManager {
    
    private static final Logger logger = LoggerFactory.getLogger(PersistenceConfigManager.class);
    
    private static final String PERSISTENCE_ENABLED_KEY = "datalink.persistence.enabled";
    private static final String PERSISTENCE_STRATEGY_KEY = "datalink.persistence.strategy";
    private static final String PERSISTENCE_CRITICAL_ACTORS_KEY = "datalink.persistence.critical.actors";
    private static final String PERSISTENCE_BUSINESS_ACTORS_KEY = "datalink.persistence.business.actors";
    
    private static volatile PersistenceConfigManager instance;
    
    private final Map<String, Boolean> actorTypeConfig = new ConcurrentHashMap<>();
    private final Map<String, Boolean> instanceConfig = new ConcurrentHashMap<>();
    
    private PersistenceConfigManager() {
        loadConfiguration();
    }
    
    public static PersistenceConfigManager getInstance() {
        if (instance == null) {
            synchronized (PersistenceConfigManager.class) {
                if (instance == null) {
                    instance = new PersistenceConfigManager();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化配置管理器
     */
    public void initialize() {
        logger.info("Initializing PersistenceConfigManager");
        // 这里可以添加初始化逻辑，比如加载配置文件等
    }
    
    /**
     * 判断指定的Actor是否应该启用持久化
     * 
     * @param nodeId Actor节点ID
     * @param actorType Actor类型
     * @param properties Actor属性
     * @return true表示启用持久化，false表示不启用
     */
    public boolean shouldPersist(String nodeId, String actorType, Map<String, Object> properties) {
        // 全局开关检查
        if (!isGlobalPersistenceEnabled()) {
            return false;
        }
        
        // 策略检查
        String strategy = getStrategy();
        if ("none".equals(strategy)) {
            return false;
        }
        
        if ("all".equals(strategy)) {
            return true;
        }
        
        // 选择性策略：按优先级检查
        return checkPersistenceDecision(nodeId, actorType, properties);
    }
    
    /**
     * 检查全局持久化是否启用
     */
    public boolean isGlobalPersistenceEnabled() {
        return Boolean.parseBoolean(System.getProperty(PERSISTENCE_ENABLED_KEY, "false"));
    }
    
    /**
     * 获取持久化策略
     */
    public String getStrategy() {
        return System.getProperty(PERSISTENCE_STRATEGY_KEY, "selective");
    }
    
    /**
     * 设置Actor类型的持久化配置
     */
    public void setActorTypePersistence(String actorType, boolean enabled) {
        actorTypeConfig.put(actorType, enabled);
        logger.info("Set actor type persistence: {} = {}", actorType, enabled);
    }
    
    /**
     * 设置Actor实例的持久化配置
     */
    public void setInstancePersistence(String nodeId, boolean enabled) {
        instanceConfig.put(nodeId, enabled);
        logger.info("Set instance persistence: {} = {}", nodeId, enabled);
    }
    
    /**
     * 获取Actor类型的持久化配置
     */
    public Boolean getActorTypePersistence(String actorType) {
        return actorTypeConfig.get(actorType);
    }
    
    /**
     * 获取Actor实例的持久化配置
     */
    public Boolean getInstancePersistence(String nodeId) {
        return instanceConfig.get(nodeId);
    }
    
    /**
     * 重新加载配置
     */
    public void reloadConfiguration() {
        loadConfiguration();
        logger.info("Persistence configuration reloaded");
    }
    
    private void loadConfiguration() {
        // 加载关键Actor配置
        String criticalActors = System.getProperty(PERSISTENCE_CRITICAL_ACTORS_KEY, "RuleActor,ScheduleNodeActor");
        if (criticalActors != null && !criticalActors.trim().isEmpty()) {
            for (String actorType : criticalActors.split(",")) {
                actorTypeConfig.put(actorType.trim(), true);
            }
        }
        
        // 加载业务Actor配置
        String businessActors = System.getProperty(PERSISTENCE_BUSINESS_ACTORS_KEY, "");
        if (businessActors != null && !businessActors.trim().isEmpty()) {
            for (String actorType : businessActors.split(",")) {
                actorTypeConfig.put(actorType.trim(), true);
            }
        }
        
        logger.info("Loaded persistence configuration: global={}, strategy={}, actorTypes={}", 
                   isGlobalPersistenceEnabled(), getStrategy(), actorTypeConfig);
    }
    
    private boolean checkPersistenceDecision(String nodeId, String actorType, Map<String, Object> properties) {
        // 1. 实例级配置（最高优先级）
        if (instanceConfig.containsKey(nodeId)) {
            return instanceConfig.get(nodeId);
        }
        
        // 2. Actor类型配置
        if (actorTypeConfig.containsKey(actorType)) {
            return actorTypeConfig.get(actorType);
        }
        
        // 3. 业务规则配置
        return checkBusinessRules(properties);
    }
    
    private boolean checkBusinessRules(Map<String, Object> properties) {
        if (properties == null) {
            return false;
        }
        
        // 检查是否为有状态节点
        Boolean stateful = (Boolean) properties.get("stateful");
        if (stateful != null && stateful) {
            return Boolean.parseBoolean(System.getProperty("datalink.persistence.rules.stateful-nodes", "true"));
        }
        
        // 检查是否为关键节点
        Boolean critical = (Boolean) properties.get("critical");
        if (critical != null && critical) {
            return Boolean.parseBoolean(System.getProperty("datalink.persistence.rules.critical-nodes", "true"));
        }
        
        // 默认不持久化
        return false;
    }

    /**
     * 判断是否需要持久化特定消息
     */
    public boolean shouldPersistMessage(String nodeId, String messageType) {
        if (!isGlobalPersistenceEnabled()) {
            return false;
        }

        // 检查消息类型黑名单
        String blacklistKey = "datalink.persistence.message.blacklist";
        String blacklist = System.getProperty(blacklistKey, "HeartbeatMessage,PingMessage");
        if (blacklist.contains(messageType)) {
            return false;
        }

        // 检查节点特定的消息持久化配置
        String nodeMessageKey = "datalink.persistence.node." + nodeId + ".messages";
        String nodeMessages = System.getProperty(nodeMessageKey, "all");

        if ("none".equals(nodeMessages)) {
            return false;
        } else if ("all".equals(nodeMessages)) {
            return true;
        } else {
            // 检查特定消息类型列表
            return nodeMessages.contains(messageType);
        }
    }

    /**
     * 获取Actor类型配置
     */
    public Map<String, Boolean> getActorTypeConfigs() {
        return new HashMap<>(actorTypeConfig);
    }

    /**
     * 获取实例配置
     */
    public Map<String, Boolean> getInstanceConfigs() {
        return new HashMap<>(instanceConfig);
    }

    /**
     * 获取存储路径
     */
    public String getStoragePath() {
        return System.getProperty("datalink.persistence.storage.path", "data/persistence");
    }

    /**
     * 设置全局持久化开关
     */
    public void setGlobalPersistenceEnabled(boolean enabled) {
        System.setProperty("datalink.persistence.enabled", String.valueOf(enabled));
        logger.info("Global persistence enabled set to: {}", enabled);
    }

    /**
     * 设置持久化策略
     */
    public void setPersistenceStrategy(String strategy) {
        System.setProperty("datalink.persistence.strategy", strategy);
        logger.info("Persistence strategy set to: {}", strategy);
    }

    /**
     * 删除Actor类型持久化配置
     */
    public void removeActorTypePersistence(String actorType) {
        actorTypeConfig.remove(actorType);
        logger.info("Removed actor type persistence: {}", actorType);
    }

    /**
     * 删除实例持久化配置
     */
    public void removeInstancePersistence(String instanceId) {
        instanceConfig.remove(instanceId);
        logger.info("Removed instance persistence: {}", instanceId);
    }

    /**
     * 清空所有配置
     */
    public void clearAllConfigurations() {
        actorTypeConfig.clear();
        instanceConfig.clear();
        logger.info("Cleared all persistence configurations");
    }

    /**
     * 设置批处理大小
     */
    public void setBatchSize(int batchSize) {
        System.setProperty("datalink.persistence.batch.size", String.valueOf(batchSize));
        logger.info("Set batch size to: {}", batchSize);
    }

    /**
     * 设置异步处理
     */
    public void setAsyncProcessing(boolean async) {
        System.setProperty("datalink.persistence.async", String.valueOf(async));
        logger.info("Set async processing to: {}", async);
    }

    /**
     * 设置并发线程数
     */
    public void setConcurrentThreads(int threads) {
        System.setProperty("datalink.persistence.threads", String.valueOf(threads));
        logger.info("Set concurrent threads to: {}", threads);
    }

    /**
     * 设置批处理超时时间
     */
    public void setBatchTimeout(int timeout) {
        System.setProperty("datalink.persistence.batch.timeout", String.valueOf(timeout));
        logger.info("Set batch timeout to: {}ms", timeout);
    }

    /**
     * 设置缓存大小
     */
    public void setCacheSize(int cacheSize) {
        System.setProperty("datalink.persistence.cache.size", String.valueOf(cacheSize));
        logger.info("Set cache size to: {}", cacheSize);
    }

    /**
     * 设置垃圾回收策略
     */
    public void setGcStrategy(String strategy) {
        System.setProperty("datalink.persistence.gc.strategy", strategy);
        logger.info("Set GC strategy to: {}", strategy);
    }
}
